/* ---------------------------------------------------------------- 上传 -- */
export default {
    upload(sourceType, formData){
        let self = this;
        const token = wx.getStorageSync('token');
        const resApi = api + 'file/uploadOSS';
        return new Promise((resolve,reject)=>{
            wx.chooseMedia({
                count: 1, // 默认9
                sizeType: ['original', 'compressed'],               // 可以指定是原图还是压缩图，默认二者都有
                sourceType: [sourceType],                           // 可以指定来源是相册还是相机，默认二者都有 ['album', 'camera']
                success(res) {
                    res.tempFilePaths.forEach((v) => {
                        self.uploadFile(resApi, token, v, formData, data => {
                            resolve(data);
                        })
                    })
                }
            })
        })
    },
    uploadFile(api,token,filePath, formData, callback) {
        wx.showLoading({ title: '上传图片中...' });
        wx.uploadFile({
            header: { 'Content-Type': 'multipart/form-data', UB_UserAgent_plat: 'WECHATM', UB_UserAgent_appUserAuthToken: token },
            url: api,
            filePath: filePath,
            name: 'Filedata',
            formData: formData || {},
            success: function (res) {
                if (res.statusCode == 200) {
                    let resData = JSON.parse(res.data);
                    let code = resData.status;
                    let data = resData.data;
                    if (code === 200) {
                        callback(data);
                    } else if (code ===201) {
                        wx.showToast({ title: resData['msg'], icon: 'none' })
                        setTimeout(() => {
                            wx.redirectTo({ url: '/pages/login/index' });
                        }, 1500)
                    } else if (code === 202) {
                        wx.showToast({ title: '请先登录', icon: 'none' })
                        wx.redirectTo({ url: '/pages/login/index' });
                    } else {
                        wx.showToast({ title: '上传失败', icon: 'none' })
                    }
                    wx.hideLoading();
                } else {
                    wx.showToast({ title: '服务请求出错', icon: 'none' })
                }
            },
            fail() {
                wx.getNetworkType({
                    success(res) {
                        if (res.networkType === 'none') {
                            wx.showToast({ title: '无网络', icon: 'none' })
                        } else {
                            wx.showToast({ title: '服务请求出错', icon: 'none' });
                        }
                    }
                })
                wx.hideLoading();
            }
        })
    }
}